<?php
namespace app\index\controller;
use think\Controller;

class Base extends Controller
{   public $city = '';
    public $account = '';
    public function _initialize()
    {
        $citys = model('City')->getNormalCitys();
        $this->getCity($citys);

        //获取首页分类数据
        $cats = $this->getRecommendCats();
        $this->assign('citys', $citys);
        $this->assign('city',$this->city);
        $this->assign('user',$this->getLoginUser());
        $this->assign('cats',$cats);
        $this->assign('controller',strtolower(request()->controller()));
        $this->assign('title','o2o团购网');
    }

    public function getCity($citys)
    {
        foreach ($citys as $city) {
            $city = $city->toArray();
            if($city['is_default'] == 1) {
                $defaultname = $city['uname'];
                break;
            }
        }

       $defaultname = empty($defaultname) ? 'beijing' : $defaultname;
        //session存在并且没有点击切换城市
        if(session('cityuname','','o2o') && !input('get.city')){
            $cityuname = session('cityuname','','o2o');
        }else{
            //点击切换城市。不点击就是默认的defaultname
            $cityuname = input('get.city',$defaultname,'trim');
            session('cityuname',$cityuname,'o2o');
        }
       $this->city =  model('City')->where(['uname'=>$cityuname])->find();
    }

    public function getLoginUser() {
        if(!$this->account) {
            $this->account = session('o2o_user', '', 'o2o');
        }
        return $this->account;
    }
        //获取首页推荐分类数据
    public function getRecommendCats(){
        //一级id
        $parentIds = [];
        //二级分类 [ 父id ] id,name
        $seCatArr = [];
        //一级和二级数据，
        $recomCats = [];
        //一级分类
        $cats = model('Category')->getNormalRecommendCategoryByParentId(0,5);
       foreach($cats as $cat){
           $parentIds[] = $cat->id;
       }
       //二级分类
        $seCats = model('Category')->getNormalCategoryIdByParentId($parentIds);
       foreach($seCats as $sedCat){
            $seCatArr[$sedCat->parent_id][] =[
                'id' => $sedCat->id,
                'name' => $sedCat->name,
            ];
       }
       foreach($cats as $cat){
           //第一个参数是一级分类name.第二个参数是一级分类下所有二级分类id,name
            $recomCats[$cat->id] = [$cat->name,empty($seCatArr[$cat->id]) ? [] : $seCatArr[$cat->id]];
       }
    return ;
    }

}